package io;

import java.io.*;
import java.util.Date;

// 1. 序列化的类必须实现Serializable接口（标记接口，无方法）
class User implements Serializable {
    // 序列化版本号（确保反序列化时版本一致）
    private static final long serialVersionUID = 1L;

    private String name;
    private int age;
    private transient String password; // transient修饰的字段不被序列化
    private Date registerDate;

    public User(String name, int age, String password) {
        this.name = name;
        this.age = age;
        this.password = password;
        this.registerDate = new Date();
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", password='" + password + '\'' + // 反序列化后为null
                ", registerDate=" + registerDate +
                '}';
    }
}

public class ObjectStreamDemo {
    public static void main(String[] args) {
        String objectFile = "user.obj";
        User user = new User("张三", 25, "123456");

        // 1. 序列化：对象→字节序列
        try (ObjectOutputStream oos = new ObjectOutputStream(
                new FileOutputStream(objectFile))) {

            oos.writeObject(user);
            System.out.println("对象序列化完成：" + user);

        } catch (IOException e) {
            e.printStackTrace();
        }

        // 2. 反序列化：字节序列→对象
        try (ObjectInputStream ois = new ObjectInputStream(
                new FileInputStream(objectFile))) {

            User deserializedUser = (User) ois.readObject();
            System.out.println("对象反序列化完成：" + deserializedUser);

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
